package com.kingsgame.register;

import java.lang.reflect.Field;

import agj.hooks.BBinderListener;
import agj.hooks.BBinderUtil;
import android.app.ActivityThread;
import android.content.Context;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Process;
import android.os.ServiceManager;
import android.util.Log;

import com.albd.utils.ShellCommand;
import com.albd.utils.SystemDef;
import com.kingsgame.sdks.systemservice.TyuServiceManagerService;

public class RegisterEntry implements Runnable
{
	public static Context sContext = null;
	public static Handler sHandler = null;
	public static BBinderListener mListener;

	public static void main(String[] args)
	{
		RegisterEntry registerEntry = new RegisterEntry();
		Looper mainLooper = Looper.getMainLooper();

		if(mainLooper != null)
		{
			sHandler = new Handler(mainLooper);
			sHandler.post(registerEntry);
		}
		else
		{
			try
			{
				Field mSystemContextField = ActivityThread.class.getDeclaredField("mSystemContext");
				mSystemContextField.setAccessible(true);
				sContext = (Context) mSystemContextField.get(null);								
			}
			catch (Exception e)
			{
				Log.e("RegisterEntry", "init eror", e);
			}
			registerEntry.run();
		}
	}

	@Override public void run()
	{
		Log.i("RegisterEntry", RegisterEntry.class.getName() + ".main()");
		try
		{
			if(sContext == null)
			{
				sContext = ActivityThread.currentActivityThread().getApplication();
			}

			String app = ShellCommand.getProcessName(Process.myPid());
			int end = app.indexOf(":");
			if(end > 0)
				app = app.substring(0, end);
			Log.i("RegisterEntry", "init log file for " + app);
		
			addSystemService(app);//todo ydy
			
			bindHookListerner(app);
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/*
	 * 添加系统服务
	 */
	private void addSystemService(String app){
		
		if(app.equals(SystemDef.PRO_SERVER)){
			IBinder vTmp = ServiceManager.getService(TyuServiceManagerService.NAME);
			if(vTmp == null){
				ServiceManager.addService(TyuServiceManagerService.NAME, new TyuServiceManagerService(sContext));
			}				
		}
	}
	
	/*
	 * 实现binder监控
	 */
	
	private void bindHookListerner(String app){
		  Log.v("RegisterEntry", "start load so start!!!!!");
		mListener = new BBinderListener();
	    Log.v("RegisterEntry", "start load so...... "+app);
		BBinderUtil.buildEnv();
		BBinderUtil.setBinderHook(RegisterEntry.mListener, 0x05);
		Log.i("RegisterEntry", "Monitor started");
		mListener.initBinderFunc(app);
	}
	
	
}
